#include "dialog.h"
#include "ui_dialog.h"

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
    connect(&threadA, SIGNAL(started()), this, SLOT(threadA_started()));
    connect(&threadA, SIGNAL(finished()), this, SLOT(threadA_finished()));
    //connect(&threadA, SIGNAL(newValue(int,int)), this, SLOT(threadA_newValue(int,int))); //sample 13 -1
    connect(&dTimer, SIGNAL(timeout()), this, SLOT(onTimeOut()));
}

Dialog::~Dialog()
{
    delete ui;
}

void Dialog::threadA_started(){
    ui ->label->setText("Thread状态， 启动");
}

void Dialog::threadA_finished(){
    ui->label->setText("Thread状态， 结束");
}

//void Dialog::threadA_newValue(int seq, int diceValue){
//    QString str = QString::asprintf("第 %d 次掷骰子，点数为 %d ", seq, diceValue);
//    ui -> plainTextEdit -> appendPlainText(str);
//}

void Dialog::on_threadStart_clicked()
{
    dSeq = 0;
    threadA.start();
    ui->threadStart->setEnabled(false);
    ui->start->setEnabled(true);
    ui->pause->setEnabled(false);
    ui->stopThread->setEnabled(true);
}

void Dialog::on_start_clicked()
{
    threadA.diceBegin();
    dTimer.start(100);//定时器100ms读取一次数据
    ui->start->setEnabled(false);
    ui->pause->setEnabled(true);

}

void Dialog::on_pause_clicked()
{
    threadA.dicePause();
    dTimer.stop();
    ui->start->setEnabled(true);
    ui->pause->setEnabled(false);
}

void Dialog::on_stopThread_clicked()
{
    threadA.threadStop();
    threadA.wait();
    ui->threadStart->setEnabled(false);
    ui->start->setEnabled(false);
    ui->pause->setEnabled(false);
    ui->threadStart->setEnabled(true);
}

void Dialog::on_clearText_clicked()
{
    ui -> plainTextEdit->clear();
}

void Dialog::closeEvent(QCloseEvent *event){
    if (threadA.isRunning()){
        threadA.threadStop();
        threadA.wait();
    }
    event->accept();
}

void Dialog::onTimeOut(){
    int tempSeq = 0, tempValue = 0;
    //通过readValue把骰子类的值的指针变量的值赋值给temp的地址
    bool valid = threadA.readValue(&tempSeq, &tempValue);//读取数据
    if (valid && (tempSeq != dSeq)){//有效，并且是新数据
        dSeq = tempSeq;
        dDiceValue = tempValue;
        QString str = QString::asprintf("第 %d 次掷骰子，点数为 %d ", dSeq, dDiceValue);
        ui -> plainTextEdit ->setPlainText(str);
    }
}
